package com.dy.tieba.serviceImpl;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.dy.tieba.db.Posts;
import com.dy.tieba.db.RobotPost;
import com.dy.tieba.db.TieBaPost;
import com.dy.tieba.service.PostService;
import lib.BasicService;
import lib.Execute;
import lib.MySQLHelper;
import service.ws.BareResponseProcessor;
import service.ws.CommonWSHandler;
import service.ws.WSHandler;
public class PostServiceImpl extends BasicService implements PostService{
	/**
	 * 得到文章
	 * @author qicf
	 * @param startPage
	 */
	@Override
	public List<Posts> getPosts(String sql ,int startPage, int pageSize, String order) throws Exception {
		String sqlStr = String.format("post_type = 'post' and post_status= 'publish' order by ID %s limit %s, %s",StringUtils.isNoneBlank(order)?order:"asc", startPage*10,pageSize);
		if(StringUtils.isNoneBlank(sql)){
			sqlStr = String.format("%s and %s", sql, sqlStr);
		}
		List<Posts> posts = MySQLHelper.find(Posts.class, sqlStr);
		return posts;
	}

	/**
	 * 贴吧发帖纪录
	 */
	@Override
	public List<TieBaPost> getTieBaPost(String sql, int startPage, int pageSize, String order) throws Exception {
		String sqlStr = String.format("1=1 order by id %s limit %s, %s",StringUtils.isNoneBlank(order)?order:"asc",startPage*10,pageSize);
		if(StringUtils.isNoneBlank(sql)){
			sqlStr = String.format("% and %s", sql, sqlStr);
		}
		return MySQLHelper.find(TieBaPost.class, sqlStr);
	}
	
	@Override
	public Map<String, Object> postTieba() throws Exception{
		List<TieBaPost> tieBaPosts = getTieBaPost("", 0, 1, "desc");
		List<Posts> posts = null;
		List<RobotPost> robots = null;
		//得到最新的发帖纪录
		if(tieBaPosts!=null && !tieBaPosts.isEmpty()){
			TieBaPost tieBaPost = tieBaPosts.get(0);
			Long postId = tieBaPost.postId;
			//得到postId的下一条纪录
			posts = getPosts("ID>"+postId, 0, 1, "asc");
			if(posts==null || posts.isEmpty()){
				posts = getPosts("", 0, 1, "asc");
			}
			//得到最近的发帖用户的下一条纪录
			robots = userRobotService.getRobots("id>"+tieBaPost.userId, 0, 1, "asc");
			if(robots==null || robots.isEmpty()){
				robots = userRobotService.getRobots("", 0, 1, "asc");
			}
		}else{
			posts = getPosts("", 0, 1, "asc");
			robots = userRobotService.getRobots("", 0, 1, "asc");
		}
		
		Posts post = posts.get(0);
		RobotPost robotPost = robots.get(0);
		return post(post, robotPost);
	}
	
	public Map<String,Object> post(Posts post, RobotPost robotPost) throws ParseException, IOException, SQLException{
		Map<String,Object> resultDate = new HashMap<>();
		String post_title = post.post_title;
		String codeTitme = URLEncoder.encode(post_title,"utf-8");
		System.out.println("用户:"+robotPost.userName+" 正在《"+post_title+"》发帖...");
		WSHandler wsHandler = new CommonWSHandler("https://tieba.baidu.com/f?kw="+codeTitme+"&ie=utf-8");
		wsHandler.addHeader(new BasicHeader("Cookie", robotPost.cookie));
		wsHandler.addHeader(new BasicHeader("Accept-Encoding", "gzip, deflate, sdch"));
		wsHandler.addHeader(new BasicHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"));
		wsHandler.addHeader(new BasicHeader("Host","tieba.baidu.com"));
		wsHandler.addHeader(new BasicHeader("Accept-Language","zh-CN,zh;q=0.8"));
		wsHandler.addHeader(new BasicHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
		wsHandler.get();
		HttpResponse httpResponseget = wsHandler.process(BareResponseProcessor.getInstance());
		Document doc = Jsoup.parse(EntityUtils.toString(httpResponseget.getEntity()));
		Elements select = doc.select("script");
		String text = select.get(1).data();
		System.out.println(text);
		Pattern pattern = Pattern.compile("'tbs': \"(.*?)\"");
		Pattern pattern2 = Pattern.compile("'id': (.*?)\\,");
		Matcher matcher = pattern.matcher(text);
		Matcher matcher2 = pattern2.matcher(text);
		while (matcher.find()) {
			String tbs = matcher.group(1);
			//添加tbs
			System.out.println("tbs is:"+tbs);
			wsHandler.addParam("tbs", tbs);
			break;
		}
		int index = 0;
		while (matcher2.find()) {
			if(index == 1) {
				String fid = matcher2.group(1);
				//fid,贴吧的id
				System.out.println("fid is:"+fid);
				wsHandler.addParam("fid", fid);
				break;
			}
			index ++;
		}
		String post_content = post.post_content+"[br]"+post_title+"[br][url]http://dydywang.com/"+post.id+".html[/url]";
		//发帖
		wsHandler.setMainUrl("https://tieba.baidu.com/f/commit/thread/add");
		wsHandler.addHeader(new BasicHeader("Referer","https://tieba.baidu.com/f?kw="+codeTitme+"&ie=utf-8"));
		wsHandler.addParam("kw", post_title);
		wsHandler.addParam("title", post_title);
		wsHandler.addParam("content", post_content);
		wsHandler.addParam("ie", "utf-8");
		wsHandler.addParam("tid", "0");
		wsHandler.addParam("vcode_md5", "");
		wsHandler.addParam("floor_num", "0");
		wsHandler.addParam("rich_text", "1");
		wsHandler.addParam("basilisk", "1");
		wsHandler.addParam("prefix", "");
		wsHandler.addParam("mouse_pwd_isclick", "0");
		wsHandler.addParam("__type__", "thread");
		wsHandler.addParam("_BSK", "JVwPUGcLBBl1RARvVH1HHEgQdnVgBRNWUj4CCmdGdXJrECQdRixoXwUBf21GekMHehp9GFwnDGVkXBIXKkEIRDUQXXMAIBNCHksmODRDHEVTYRdUKlg2JH1AIgZdPWgPEEIoMhdZawcgRT5AFz9WASwfDAZpUkVFJhBfHg8lG1EeDio5HFcUWlthFUM0QCMjJXk0A1YKJREZUTw0DwFJCCdLOlg3NFQiHR8NDydQR0BpFlIvFTkEVS8RIDkuVllFWyECRzZQAyY0XiQcHy4hCTZcMCcRWU8NGlwmWBt8VSYqHQkuIFVNSmkYXCkEGBkcBwgzMhhcWUVbPg5cIGEpfCNVIwZJLAYEWVQ4IzdIRgwqXDZbEHxeLjAaTQQgRWlKMRZbOgUPJWM4EikyKQdZFVB8RRxlB3ZhZgBlXgJlZg5HEWd3VRkeWWUKPgZcahh/aU5NQTAABhFnOFwlCCAaUUVSa2d6DSJeUCkIUTYVCARxBn5eCGkTMiIFaX5EbFoZJU0IURwbUTNxS1JUawISC20+ewssAFoQBg4uMnpiEFRVIk4GBl00PzxVf1oEZ3RTRwplYEocGVppez5SHyJRaGtNVk12BwYHZxQCfVtsRwReV2l1NhdXDR45FVMgGWQjYBJqTwp5dFFXVmx1Xg0YWXgfbwFPYRRlP01DWWVXRUc2EB99FX5UCkpWcGZoFUQBB3RVCmdcd3JrECQdRixoXwUAf21ES0sFOk1zFh9kGn1+GAAPNlQICTdEEWVDKgNeCRMsODQFB1ZQKQhLbRxmK3FrPg5HIDIYVVAyMwFwChRrBH1aTHICZ2xOUFR1BBUaaVdQbkN2VkQYEiB7eEFEFQRvKXMJeWR8c11hTQlrJhwGWjE+F0Z1CAVeb14ZchRlMk9DWWdLTAYGOxFzQzhHElBFIyI0RgFeUSNHUipmMiI4XjdHGmk/XS5dPCMNW09JKkc7USNwRWVyXBZRZwsGZRA5f31NbgYBSF1ncm1nUAUMOQVVYAd0dWJxdV0BfnVPFgtsY1QcHAosG2ZQR2ENdmxOUFVyAxAOd0cWaCVuWhIdVmdteGsge3JvGg==");
		wsHandler.post();
		HttpResponse httpResponse = wsHandler.process(BareResponseProcessor.getInstance());
	    String responseString = EntityUtils.toString(httpResponse.getEntity());
	    JSONObject result = new JSONObject(responseString);
	    System.out.println(result);
	    int no = result.getInt("no");
	    if(no==0) {
	    	System.out.println("用户:"+robotPost.userName+" 在《"+post_title+"》发帖成功");
	    	JSONObject data = result.getJSONObject("data");
	    	//帖子链接
	    	String tidUrl = "http://tieba.baidu.com/p/"+data.getLong("tid");
	    	System.out.println("帖子URl："+tidUrl);
	    	MySQLHelper.withTransaction(new Execute() {
				@Override
				public void call() throws Exception {
					long id = executeUpdateResponse("insert into wp_tieba_post (postId,userId,tiebaUrl,publishTime) value (?,?,?,?)", post.id, robotPost.id, tidUrl, new Date());
					resultDate.put("id", id);
					resultDate.put("code", 200);
				}
			});
	    }else {
	    	System.out.println("发帖失败");
	    	resultDate.put("code", 500);
	    }
		return resultDate;
	}
}
